﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Core.Model;
using Channel = Core.Model.Channel;

namespace DataServer.View
{
    /// <summary>
    /// DeviceView.xaml 的交互逻辑
    /// </summary>
    public partial class RealTimeView
    {
       // private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private readonly ObservableCollection<Channel> _channels = new ObservableCollection<Channel>();
        private readonly ObservableCollection<Device> _devices = new ObservableCollection<Device>();
        private Channel selectChannel;
        private Device selectDevice;
        private readonly ObservableCollection<DataItem> _dataItems = new ObservableCollection<DataItem>();

        public RealTimeView()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            this.Loaded += RealTimeView_Loaded; 
        }

        private void RealTimeView_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateBinding();
            if (AppManager.IsInit)
            {
                btnStartComm.IsEnabled = !AppManager.IsRunning;
                btnStopComm.IsEnabled = AppManager.IsRunning;
            }
            else
            {
                btnStartComm.IsEnabled = false;
                btnStopComm.IsEnabled = true;
            }
        }

        private void UpdateBinding()
        {
            channelListBox.DataContext = null;
            _channels.Clear();
            List<Channel> channels = AppManager.ChannelDao.GetEntities();
            if (channels != null)
            {
                foreach (Channel ch in channels)
                {
                    _channels.Add(ch);
                }
            }
            channelListBox.DataContext = _channels;
            if (_channels.Count > 0)
            {
                channelListBox.SelectedItem = _channels[0];
            }
        }
        private void ChannelListBox_OnMouseUp(object sender, MouseButtonEventArgs e)
        {
            selectDevice = null;
        }
        private void ChannelListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectDevice = null;
            selectChannel = channelListBox.SelectedItem as Channel;
           
            _devices.Clear();
            if (selectChannel != null)
            {
                List<Device> devices = AppManager.DeviceDao.GetDevicesByChlId(selectChannel.Id);
                if (devices != null)
                {
                    foreach (Device dev in devices)
                    {
                        dev.DeviceType = AppManager.DeviceTypeDao.GetEntityById(dev.DeviceTypeId);
                        var memDev = AppManager.GetDeviceById(dev.ChannelId, dev.Id);
                        if (memDev != null)
                            dev.IsConnected = memDev.IsConnected;
                        //else
                        //    dev.IsConnected = false;
                        _devices.Add(dev);
                    }
                }
                deviceListBox.DataContext = _devices;
                if(_devices.Count>0)
                    deviceListBox.SelectedItem = _devices[0];

                txtChannelId.Text = selectChannel.Id; // 
            }
            else
            {
               
                txtChannelId.Text = ""; // 
            }
            deviceListBox.InvalidateVisual();
        }
        private void DeviceListBox_OnMouseUp(object sender, MouseButtonEventArgs e)
        {
            selectDevice = deviceListBox.SelectedItem as Device;
            UpdateDataItems();
        }
        private void DeviceListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new Action((() =>
            {
                selectDevice = deviceListBox.SelectedItem as Device;
                UpdateDataItems();
            })),DispatcherPriority.ApplicationIdle);
        }
        private void BtnStartComm_OnClick(object sender, RoutedEventArgs e)
        {
            WaitingBox.Show(this, () =>
            {
                AppManager.StartCommunication();
                AppManager.StartTransmit();

            }, "正在启动通信任务，请稍后...");
            //Thread.Sleep(1000);
            btnStartComm.IsEnabled = false;
            btnStopComm.IsEnabled = true;
            UpdateBinding();
           
        }
        private void BtnStopComm_OnClick(object sender, RoutedEventArgs e)
        {

            WaitingBox.Show(this, () =>
            {
                AppManager.StopCommunication();
                AppManager.StopTransmit();

            }, "正在停止通信任务，请稍后...");
            btnStartComm.IsEnabled = true;
            btnStopComm.IsEnabled = false;
            UpdateBinding();
           
        }

        public void UpdateDataItems()
        {
            if (selectDevice == null)
            {
                _dataItems.Clear();
                txtDeviceId.Text = "";
                return;
            }
            txtDeviceId.Text = selectDevice.Id; //

            List<DataItem> dataItems;
            if (AppManager.IsRunning)
            {
                dataItems = AppManager.GetDataItemsByDevice(selectDevice);
                _dataItems.Clear();
                if (dataItems?.Count > 0)
                {
                    foreach (DataItem item in dataItems)
                    {
                        _dataItems.Add(item);
                    }
                }
                _gridDataItem.ItemsSource = _dataItems;
                return;
            }

            
            _dataItems.Clear();
            dataItems = Core.Global.DataAccess.GetDataItems(selectDevice.Id);
            if (dataItems?.Count > 0)
            {
                foreach (DataItem item in dataItems)
                {
                    _dataItems.Add(item);
                }
            }
            _gridDataItem.ItemsSource = _dataItems;

        }


        private void _gridDataItem_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = _gridDataItem.SelectedItem as DataItem;
            if (item == null)
            {
                txtItemId.Text = "";
            }
            else
            {
                txtItemId.Text = item.Id;
            }
        }
    }
}
